﻿<!DOCTYPE html>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>DOM Manipulation - LiveNodeLists Performance</title>
	<style>
		.hidden {
			display: none;
		}
	</style>
</head>
<body>
	<div id="content"></div>
	<a href="http://jsperf.com/livenodelists-length/3">Better example at jsperf.com</a>
	<script>

		/* preparation code */
		var hiddenDiv = document.createElement("div");
		hiddenDiv.classList.add("hidden");
		var count = 100000;
		var docFragment = document.createDocumentFragment();
		for (var i = 0; i < count; i++) {
			docFragment.appendChild(hiddenDiv.cloneNode(true));
		}
		document.getElementById("content").appendChild(docFragment);

		/* end of preparation code */

		function regularLoop(elements) {
			for (var i = 0; i < elements.length; i++) {
				elements[i];
			}
		}

		function cachedLengthLoop(elements) {
			for (var i = 0, len = elements.length; i < len; i++) {
				elements[i];
			}
		}

		var divs = document.getElementsByClassName("hidded"),startTime,endTime;
		startTime = new Date();
		regularLoop(divs);
		endTime = new Date();
		console.log("regular loop executed in " + (endTime - startTime));

		startTime = new Date();
		cachedLengthLoop(divs);
		endTime = new Date();
		console.log("loop with cached length executed in " + (endTime - startTime));


	</script>
</body>
</html>
